const App = {
  mixins: [Query], //配置文件，路径/utils/mixins.js
  data() {
    return {
      // 水印配置
      // watermarkText: "",
      // watermarkFont: "16px Arial",
      // watermarkAlpha: 0.2,
      // watermarkZIndex: 999,
      // // 新增水印配置
      // // watermarkFont: "14px Microsoft YaHei", // 字体样式
      // watermarkRepeat: "repeat", // 重复方式，如 repeat、no-repeat 等
      // watermarkX: 0, // 水平偏移
      // watermarkY: 0, // 垂直偏移
      // watermarkWidth: 200, // 水印单元宽度
      // watermarkHeight: 100, // 水印单元高度
      // watermarkAlpha: 0.2, // 透明度（0~1）
      // watermarkZIndex: 1000, // 层级，确保在内容下方但不被遮挡
      currentRow: [],
      showDialogDelete: false,
      category: [],
      village: [],
      page: {
        value1: "",
        value2: "",
        PageNumber: 1, //页码
        RowAmount: 10,
        Condition: window.btoa(unescape(encodeURIComponent("%%,%%,%%"))),
        //Condition:"",
      },
      deleteReasoninfo: [
        { value: "恶意投诉", label: "恶意投诉" },
        { value: "不符合事实", label: "不符合事实" },
        { value: "沟通后撤销", label: "沟通后撤销" },
        { value: "已解决", label: "已解决" },
      ],
      bdeleted: false,
      deleteReason: "",
      valueDatepick: '',
      cityValue1: '',
      // pickerOptions: {
      //     shortcuts: [{
      //       text: '最近一周',
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      //         picker.$emit('pick', [start, end]);
      //       }
      //     }, {
      //       text: '最近一个月',
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      //         picker.$emit('pick', [start, end]);
      //       }
      //     }, {
      //       text: '最近三个月',
      //       onClick(picker) {
      //         const end = new Date();
      //         const start = new Date();
      //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      //         picker.$emit('pick', [start, end]);
      //       }
      //     }]
      //   },
    };
  },
  mounted() {
    this.Init();
    this.initWatermark();
  },
  methods: {

    // 导入数据方法
    import_data() {
      window.location.href = "./import.html";
    },
    // 导出方法
    Batchexport() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "s_base_sql_table_config",
          Condition: window.btoa(
            unescape(encodeURIComponent("%" + this.relativePath + "%"))
          ),
          ExtensionCondition: "",
        },
        success: (columns) => {
          console.log(columns);
          $.ajax({
            headers: requestHeaders(),
            method: "post",
            url: mh + "/generalBusiness/generalQueryBySQLSerialNumber",
            data: {
              Model_Url: this.relativePath,
              Condition: this.page.Condition,
              ExtensionCondition: this.page.ExtensionCondition || "",
            },
            success: (data) => {
              if (data.length > 0) {
                this.$confirm(
                  `当前共查出${data.length}条数据, 是否继续?`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success",
                  }
                )
                  .then(() => {
                    console.log("点击了确认");

                    this.$prompt("请输入您导出的文件名", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                    })
                      .then(({ value }) => {
                        this.$message({
                          type: "success",
                          message: "你的文件名是: " + value,
                        });
                        if (!value) {
                          value = "未知名";
                        }
                        // return;
                        const wb = XLSX.utils.book_new();
                        const ws_data = [columns.map((i) => i.COLUMN_COMMENT)];
                        const ws_main = data.map((item) =>
                          columns.map((row) => item[row.COLUMN_NAME])
                        );
                        const ws = XLSX.utils.aoa_to_sheet([
                          ...ws_data,
                          ...ws_main,
                        ]);
                        ws["!cols"] = [];
                        for (
                          let i = 0;
                          i < Object.keys(ws_data[0]).length;
                          i++
                        ) {
                          ws["!cols"].push({ wpx: 150 });
                        }
                        XLSX.utils.book_append_sheet(wb, ws, value);
                        XLSX.writeFile(wb, value + ".xlsx");
                      })
                      .catch(() => {
                        this.$message({
                          type: "info",
                          message: "取消输入",
                        });
                      });
                  })
                  .catch((erro) => {
                    console.log(erro);
                  });
              } else {
                this.$message({
                  message: "未查询出可导出的数据!",
                  type: "warning",
                });
              }
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
          });
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    handleDelete1(data) {
      //判断Modify状态下 是否已经分配或者进入处理了
      if (data.status != "提交") {
        this.$message.error("此事件已经进入处理环节,禁止编辑!");
        return;
      }

      let _this = this;
      this.deleteReason = "";
      this.currentRow = data;
      _this.showDialogDelete = true;
    },
    deleteConfirm() {
      let _this = this;
      let _deleteReason = this.deleteReason;
      if (_deleteReason != null && _deleteReason != "") {
        _this.handleDelete(this.currentRow);
      } else {
        this.$message.error("请选择删除原因。");
        return;
      }
    },

    //删除数据
    handleDelete(data) {
      this.$confirm("该操作将删除此条数据,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let { TableName, primary_key } = JSON.parse(
            document.getElementById("table").getAttribute("data-options")
          );
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
            method: "post",
            data: {
              Data: TableName,
              Condition: primary_key + "='" + data[primary_key] + "'",
            },
            success: (res) => {
              if (res.length == 1) {
                res[0].Row_Status = "1";
                let lJSONObject_DataSet = new Object();
                let lJSONObject_Table = new Object();
                lJSONObject_Table[TableName] = res;
                lJSONObject_DataSet["Modify"] = lJSONObject_Table;
                let Operation_Main = JSON.stringify(
                  deepClone(lJSONObject_DataSet)
                );
                lJSONObject_DataSet["Add"] = new Object();
                lJSONObject_DataSet["Add"]["base_operation_log"] = [
                  {
                    Operation_Type: "0",
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress(),
                  },
                ];
                let _deleteReason = this.deleteReason;
                this.showDialogDelete = false;
                //插入删除日志表记录
                lJSONObject_DataSet["Add"]["base_delete_log"] = [
                  {
                    TableName: "complaints",
                    KeyName: "complaint_id",
                    KeyValue: data[primary_key],
                    Reason: _deleteReason,
                    BusinessName: "事件上报",
                  },
                ];

                submitSave(lJSONObject_DataSet, (res) => {
                  if (res.Status == "success") {
                    this.postgetList(this.page);
                  } else {
                    this.$message({
                      type: "error",
                      message: "删除失败",
                    });
                  }
                });
              } else {
                this.showDialogDelete = false;
                this.$message({
                  type: "error",
                  message: "删除失败",
                });
              }
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
          });
        })
        .catch(() => { });
    },
    initWatermark() {
      // 可以在这里动态设置水印内容，例如包含用户名和时间
      const userName = this.getUserNameFromCookie(); // 假设从Cookie获取用户名
      const currentTime = new Date().toLocaleString();
      // this.watermarkText = `用户: ${userName} | 时间: ${currentTime} | 机密信息`;
      this.watermarkText = `喻雯楠`;
    },
    getUserNameFromCookie() {
      // 从Cookie获取用户名的方法
      return getCookie("user") || "未知用户";
    },
    complaintsAdd() {
      window.location.href = "./add.html?action=Add";
    },
    Init() {
      //类别
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: "complaints_categories",
          Condition: "Row_Status='0'",
        },
        success: (data) => {
          this.category = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });

      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/clientOperation/getDistrictTree`,
        type: "GET",
        data: {
          DistrictCode: "232723"
        },
        success: (data) => {
          this.city1 = data[0].children;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },

    check() {
      //this.page.Condition = window.btoa(unescape(encodeURIComponent(this.page.value1 + ",%"+this.page.value2+"%")));

      let strwhere = '';

      if (this.cityValue1) {
        strwhere += " and complaints.Village_SerialNumber='" + this.cityValue1 + "'";
      }

      if (this.valueDatepick) {

        const outputDates = this.valueDatepick.map((dateStr, index) => {
          const date = new Date(dateStr);
          const year = date.getUTCFullYear();
          const month = String(date.getUTCMonth() + 1).padStart(2, '0');
          const day = String(date.getUTCDate()).padStart(2, '0');

          if (index === 0) {
            return `${year}-${month}-${day} 00:00:00`;
          } else {
            return `${year}-${month}-${day} 24:00:00`;
          }
        });

        strwhere += " and complaints.Create_Datetime>='" + outputDates[0] + "' and complaints.Create_Datetime<='" + outputDates[1] + "'"
      }


      this.page.Condition = window.btoa(
        unescape(
          encodeURIComponent(
            "%" + this.page.value1 + "%" + ",%" + this.page.value2 + "%" + ",%%"
          )
        )
      );

      if (strwhere) {
        this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(strwhere)))
      }
      this.postgetList(this.page);
    },

    getCategorys(data, arr) {
      data.forEach((item) => {
        arr.push(item.category_id);
        if (item.children && item.children.length > 0) {
          this.getCategorys(item.children, arr);
        }
      });
    },
    //树的点击筛选事件
    handleNodeClick(data, node) {
      // this.page.Condition = window.btoa(
      //   unescape(
      //     encodeURIComponent(
      //       "%" +
      //       this.page.value1 +
      //       "%" +
      //       ",%" +
      //       this.page.value2 +
      //       "%,%" +
      //       data.category_id +
      //       "%"
      //     )
      //   )
      // );


      // this.nodeKey = data.Party_Organization_SerialNumber;
      // this.nodeName = data.Party_Organization_Name;
      let arr = [];
      if (data.children) {
        this.getCategorys(data.children, arr);
      }
      let strwhereCategory_ids = "";
      [data.category_id, ...arr].forEach((item) => {
        if (strwhereCategory_ids) {
          strwhereCategory_ids += "\r\nOR complaints.category_id='" + item + "'";
        } else {
          strwhereCategory_ids = "\r\complaints.category_id='" + item + "'";
        }
      });
      if (strwhereCategory_ids) {
        strwhereCategory_ids = "AND (" + strwhereCategory_ids + ")";
      } 
      
      let strwhere = strwhereCategory_ids;

      if (this.cityValue1) {
        strwhere += " and complaints.Village_SerialNumber='" + this.cityValue1 + "'";
      }

      if (this.valueDatepick) {

        const outputDates = this.valueDatepick.map((dateStr, index) => {
          const date = new Date(dateStr);
          const year = date.getUTCFullYear();
          const month = String(date.getUTCMonth() + 1).padStart(2, '0');
          const day = String(date.getUTCDate()).padStart(2, '0');

          if (index === 0) {
            return `${year}-${month}-${day} 00:00:00`;
          } else {
            return `${year}-${month}-${day} 24:00:00`;
          }
        });

        strwhere += " and complaints.Create_Datetime>='" + outputDates[0] + "' and complaints.Create_Datetime<='" + outputDates[1] + "'"
      }
      
      if (strwhere) {

        this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(strwhere)))
      }
      this.page.Condition = window.btoa(
        unescape(
          encodeURIComponent(
            "%" +
            this.page.value1 +
            "%" +
            ",%" +
            this.page.value2 +
            "%,%%"
          )
        )
      );
      this.postgetList(this.page);
    },
    MemberAdd(row) {
      let str = row["Village_Number"];

      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./memberAdd.html?action=Modify&nodeKey=" + row[primary_key];
    },
  },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
